import { Suspense } from 'react'
import { BrowserRouter as Router, RouteObject } from 'react-router-dom'
import routes from '~react-pages'
import BasicLayout from './layout/BasicLayout'
import { any, clone, equals, filter, map, pipe } from 'ramda'
import LoadingPage from './components/LoadingPage'
import { useRouteMetas, RouteMeta } from './config/route-meta'
import BasicLayout3 from './layout/BasicLayout3'
import BasicLayout2 from './layout/BasicLayout2'

export default function App() {
  return (
    <Router>
      <Routes />
    </Router>
  )
}

function Routes() {
  const routeMetas = useRouteMetas()
  const noLayoutRoutes = pipe(
    filter((meta: RouteMeta) => !!meta.nolayout),
    map((meta: RouteMeta) => meta.path)
  )(routeMetas)

  function pathFilter(route: RouteObject): RouteObject {
    if (any(equals(route.path))(noLayoutRoutes)) {
      return route
    } else {
      // children and element do not appear in the same route node
      if (route.children) {
        return {
          ...clone(route),
          children: clone(route.children).map(pathFilter)
        }
      } else {
        const rawElement = clone(route.element)
        route.element = <BasicLayout2>{rawElement}</BasicLayout2>
        return route
      }
    }
  }

  const routesWithLayout = clone(routes).map(pathFilter)
  //console.log(routesWithLayout)

  return (
    <Suspense fallback={<LoadingPage />}>
      {useRoutes(routesWithLayout)}
    </Suspense>
  )
}
